package com.youcheng.configcenter.refresh;

import com.youcheng.configcenter.exception.ConfigCenterServiceException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Configuration;
import javax.annotation.PostConstruct;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author sunhongmin
 * @date 2022/10/23 21:44
 * @description
 */
@Slf4j
@Configuration
@ConditionalOnProperty(name = "lightweight.config.refresh.enable", havingValue = "true")
public class RefreshScheduleExcutor extends RefreshScheduleSupport {

    private final ScheduledExecutorService scheduledExecutorService = new ScheduledThreadPoolExecutor(2, new ThreadFactory() {
        private final AtomicInteger index = new AtomicInteger(1);
        @Override
        public Thread newThread(Runnable r) {
            return new Thread(r, "SchedulePool-RefreshScheduleExcutor-" + index.getAndIncrement());
        }
    });

    @PostConstruct
    public void scheduleRefresh() {
        log.info("配置刷新定时任务开启...");
        scheduledExecutorService.scheduleAtFixedRate(() -> {
            try {
                doRefreshExcute();
            } catch (ConfigCenterServiceException e) {
                log.info("配置刷新定时任务异常...", e);
                throw new RuntimeException(e);
            }
        }, 10, Long.parseLong(environment.getProperty("lightweight.config.refresh.delay", "60")), TimeUnit.SECONDS);
    }
}
